package com.zxl.gtion.shiro.realm;

import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import com.zxl.gtion.entity.User;
import com.zxl.gtion.pojo.WxLoginInfo;
import com.zxl.gtion.service.UserService;
import com.zxl.gtion.shiro.LoginType;
import com.zxl.gtion.shiro.WxMiniToken;
import com.zxl.gtion.util.ShiroUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @Author: zh
 * @Date: 2020/9/8 9:48
 */
public class CustomWxRealm extends AuthorizingRealm {
	@Autowired
	private UserService userService;

	@Override
	public Class getAuthenticationTokenClass() {
		//支持的Token类的class
		return WxMiniToken.class;
	}

	/**
	 *  是否支持该token
	 *  Realm支持的类可以是token的子类或相同
	 * @param token
	 * @return
	 */
	@Override
	public boolean supports(AuthenticationToken token){
		return token != null && token instanceof WxMiniToken;
	}


	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
		return null;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		WxLoginInfo userInfo1 = (WxLoginInfo) token.getPrincipal();
		String openId = userInfo1.getOpenId();
		WxMaUserInfo userInfo = userInfo1.getUserInfo();

		//	根据 openId查询出用户，这里openId就相当于用户名
		User umsUser = userService.getUserByOpenId(openId);
		/**
		 * umsUser 为 null 
		 * 表示当前是个新用户，那么就数据库添加一条用户数据，
		 * 反之 用户登录则更新用户数据
		 */
		if (null == umsUser){
			User user = new User();
			user.setOpenId(openId);
			user.setNickName(userInfo.getNickName());
			user.setWxGender(userInfo.getGender());
			user.setCity(userInfo.getCity());
			user.setProvince(userInfo.getProvince());
			user.setCountry(userInfo.getCountry());
			user.setHeadImg(userInfo.getAvatarUrl());
			user.setWxUnionId(userInfo.getUnionId());
			userService.save(user);
			SimpleAuthenticationInfo ok = new SimpleAuthenticationInfo(user, "ok", this.getClass().getName());
			ShiroUtils.deleteCache(openId,LoginType.WECHAT_LOGIN.getType());
			return ok;
		}else {
			umsUser.setOpenId(openId);
			umsUser.setNickName(userInfo.getNickName());
			umsUser.setWxGender(userInfo.getGender());
			umsUser.setCity(userInfo.getCity());
			umsUser.setProvince(userInfo.getProvince());
			umsUser.setCountry(userInfo.getCountry());
			umsUser.setHeadImg(userInfo.getAvatarUrl());
			umsUser.setWxUnionId(userInfo.getUnionId());
			userService.updateById(umsUser);
			//	微信登录没密码
			SimpleAuthenticationInfo ok = new SimpleAuthenticationInfo(umsUser, "ok", this.getClass().getName());
			ShiroUtils.deleteCache(openId,LoginType.WECHAT_LOGIN.getType());
			return ok;
		}
	}
}

